/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="left-list">
    <el-card class="box-card" shadow="never">
      <el-form :rules="rules" :model="configData" class="demo-ruleForm">
        <el-form-item :label="$t('openatc.viproute.routename')" prop="name">
          <el-input v-model="configData.name" style="width: 44%"> </el-input>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
            {{ $t('openatc.viproute.editroad') }}
          </el-button>
        </el-form-item>
        <div class="tiops">
          <el-button
            type="text"
            v-if="isOpen == true"
            :style="{ color: bgcolor }"
            icon="el-icon-circle-plus-outline"
            @click="openAllRows"
            >{{ $t('openatc.button.expandall') }}</el-button
          >
          <el-button
            type="text"
            v-else
            :style="{ color: bgcolor }"
            icon="el-icon-remove-outline"
            @click="openAllRows"
            >{{ $t('openatc.button.collapseall') }}</el-button
          >
          {{ $t('openatc.viproute.move') }}
        </div>
      </el-form>
      <TimeVipLine
        @closeIcon="closeIcon"
        @delete="deleteId"
        @openIcon="openIcon"
        :route="route"
        :isOpen="isOpen"
      ></TimeVipLine>
      <!-- <div class="edit-text">
          <i class="iconfont icon-mingchengqianbiao"></i
          >{{ $t('openatc.greenwaveoptimize.routename') }}
        </div>
        <div class="name-input">
          <el-input v-model="configData.name" style="width: 30%"> </el-input>
        </div> -->
      <!-- <div class="edit-text">
          <i class="iconfont icon-mingchengqianbiao"></i
          >{{ $t('openatc.dutyroute.routeConfig') }}
        </div>
        <div style="display: flex; flex-direction: row; justify-content: flex-end">
          <el-button class="addbtn" type="primary" @click="handleAdd">{{
            $t('openatc.greenwaveoptimize.adddevice')
          }}</el-button>
        </div> -->
      <div class="btnGroup">
        <el-button class="btn" @click="handleClose">{{
          $t('openatc.button.Cancel')
        }}</el-button>
        <el-button class="btn" type="primary" @click="onOk">{{
          $t('openatc.button.OK')
        }}</el-button>
      </div>
    </el-card>
    <el-card v-show="showCard" class="tree-card" shadow="never">
      <div class="title-top">
        <div class="title">{{ $t('openatc.common.atc') }}</div>
        <!-- 删除字体图标 -->
        <el-button
          type="text"
          class="close"
          icon="el-icon-close"
          @click="handleDelete"
        ></el-button>
        <el-input
          v-model="devsfilter"
          :placeholder="$t('openatc.common.searchplaceholder')"
          style="margin: 10px 0"
        >
          <el-button
            slot="append"
            @click="getSerch"
            icon="el-icon-search"
          ></el-button>
        </el-input>
      </div>
      <div class="tree-list">
        <ORGIntersectionTree
          @checkedNodes="getCheck"
          @treeData="getTree"
          @finishLoadTree="finishLoadTree"
          :isOpenCheckbox="true"
          ref="ORGIntersectionTree"
        ></ORGIntersectionTree>
      </div>
    </el-card>
    <el-card v-if="showConfig && !showCard" class="control-list" shadow="never">
      <el-button
        type="text"
        class="schemeclose"
        icon="el-icon-close"
        @click="handleDeleteScheme"
      ></el-button>
      <div class="roadname">{{ this.roadname }}</div>
      <el-row>
        <el-col :span="24">
          <el-form
            :inline="true"
            ref="manual"
            label-position="left"
            :model="manualInfo"
            label-width="100px"
          >
            <el-form-item
              :label="$t('openatccomponents.phase.greenclear') + ':'"
              prop="intersection"
            >
              <el-input-number
                :min="0"
                :max="65535"
                :precision="0"
                :step="1"
                :controls="false"
                v-model.number="manualInfo.greenflash"
                size="mini"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              :label="$t('openatccomponents.overview.duration') + ':'"
              prop="count"
            >
              <el-input-number
                :min="0"
                :max="65535"
                :precision="0"
                :step="1"
                :controls="false"
                v-model.number="manualInfo.duration"
                size="mini"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              :label="$t('openatccomponents.overview.yellowflash') + ':'"
              prop="intersection"
            >
              <el-input-number
                :min="0"
                :max="65535"
                :precision="0"
                :step="1"
                :controls="false"
                v-model.number="manualInfo.yellow"
                size="mini"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              :label="$t('openatccomponents.overview.allred') + ':'"
              prop="intersection"
            >
              <el-input-number
                :min="0"
                :max="65535"
                :precision="0"
                :step="1"
                :controls="false"
                v-model.number="manualInfo.redclear"
                size="mini"
              ></el-input-number>
            </el-form-item>
            <el-form-item
              :label="$t('openatccomponents.phase.mingreen') + ':'"
              prop="count"
            >
              <el-input-number
                :min="0"
                :max="65535"
                :precision="0"
                :step="1"
                :controls="false"
                v-model.number="manualInfo.mingreen"
                size="mini"
              ></el-input-number>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div class="info">{{ $t('openatc.dutyroute.configInfo') }}</div>
      <div class="main">
        <intersection-direction-selection
          v-if="showConfig && !showCard"
          :agentId="this.agentid"
          :key="clickChange"
          :choosedDirection="choosedDirection"
          :choosedPedDirection="choosedPedDirection"
          :roadDirection="roadDirection"
          @handleClickCrossIcon="handleClickCrossIcon"
        />
      </div>
      <div class="sure">
        <el-button class="btn" type="primary" @click="handleOk">{{
          $t('openatc.button.OK')
        }}</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import Messagebox from '../../../components/MessageBox/index'
import DevicePanel from '../tables/device'
import TimeVipLine from './timeVipLine.vue'
import PhaseDataModel from 'openatc-components/package/kisscomps/components/IntersectionMap/crossDirection/utils'
import { getIntersectionInfo } from '../../../api/template'
import ORGIntersectionTree from '../../../components/ORGIntersectionTree/index'
import { getMessageByCode } from '../../../utils/responseMessage'
import ChoseIntersection from '../../../components/ChoseIntersection'
import { mapState } from 'vuex'
import { getTheme } from '../../../utils/auth'
// import CrossDiagramMgr from '@/EdgeMgr/controller/crossDiagramMgr'
// import { getTscControl } from '../../../api/control'
// import { getTscPhase } from '../../../api/route'// getPatternList
import {
  UpdateViproute
} from '../../../api/service'
export default {
  name: 'schemeConfiguration',
  components: {
    Messagebox,
    ORGIntersectionTree,
    TimeVipLine,
    DevicePanel,
    ChoseIntersection
  },
  props: {
    chooseId: {
      type: Number
    },
    editRoute: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      routeData: {},
      // isClose: true,
      showCard: false,
      clickChange: false,
      bgcolor: getTheme() === 'light' ? '#303133' : '#ffffff',
      choosedPedDirection: [],
      choosedDirection: [],
      showConfig: false,
      // roadDirection: 'left',
      route: {},
      // direction: [],
      peddirection: [],
      devsfilter: '',
      agentid: '0',
      isOpen: false,
      roadname: '',
      manualInfo: {
        greenflash: 6,
        duration: 600, // 控制方式手动操作的情况下的持续时间的临时值。
        yellow: 3,
        redclear: 2,
        mingreen: 15,
        iconList: [],
        direction: [],
        peddirection: []
      },
      chooseData: [],
      checkData: [],
      rules: {
        name: [
          {
            required: true,
            message: this.$t('openatc.viproute.routenamenull'),
            trigger: 'blur'
          }
        ]
      },
      // configurationVisible: false, // 配置界面是否显示
      activeTab: 'pattern',
      finalLists: [],
      messageboxVisible: false, // 关闭界面二期确认弹窗是否显示
      configData: {}, // 内部可修改的配置数据
      deviceIds: [], // 初始协调线路包含的设备id
      devicesData: [], // 设备面板数据
      patternData: [], // 方案面板数据
      defaultScheme: { // 默认协调方案配置参数
        sortid: 0,
        patternid: 0,
        patterndes: ''
      },
      sidewalkPhaseData: [], // 行人相位数据
      phaseList: [] // 相位列表
    }
  },
  watch: {
    chooseId: {
      handler: function (val) {
        if (val) {
          this.showCard = false
        }
      },
      immediate: true
    },
    route: {
      handler: function (val) {
        this.configData = JSON.parse(JSON.stringify(val))
        this.route = val
        this.$emit('onRouteChange', this.route)
        this.finalLists = val.devs
        // this.chooseData =
      },
      deep: true
    },
    routeData: {
      handler: function (val) {
        this.devicesData = []
        this.patternData = []
        this.configData = JSON.parse(JSON.stringify(val))
        // this.setDeviceData()
      },
      deep: true
    }
  },
  computed: {
    ...mapState({
      roadDirection: state => state.globalParam.roadDirection
    })
  },
  mounted () {
    if (this.editRoute && this.editRoute.devs && this.editRoute.devs.length > 0) {
      this.route = this.editRoute
      for (let item of this.route.devs) {
        // if (item.data.data) {
        item.duration = item.data.data.duration
        item.iconList = item.data.data.iconList
        item.direction = item.data.data.direction
        item.peddirection = item.data.data.peddirection
        // this.choosedDirection = item.data.data.direction
        // this.choosedPedDirection = item.data.data.peddirection
        // }
      }
    }
    this.$refs.ORGIntersectionTree.getDeviceRanges(this.devsfilter).then(res => {
      this.checkData = res.filter(item => {
        if (this.chooseId && this.chooseId !== 0) {
          return this.editRoute.devs.some(ele => ele.agentid === item.agentid)
        }
      })
    })
    this.PhaseDataModel = new PhaseDataModel()
  },
  created () {
  },
  methods: {
    handleOk () {
      this.showConfig = false
      this.route.devs.forEach(item => {
        if (this.agentid === item.agentid) {
          item.data = JSON.parse(JSON.stringify({ data: this.manualInfo, control: 101, duration: this.manualInfo.duration }))
          this.chooseData.push(item)
        }
      })
      this.route = JSON.parse(JSON.stringify(this.route))
    },
    openAllRows () {
      this.isOpen = !this.isOpen
    },
    handleClickCrossIcon (allChoosedDir, curClickedPhase) {
      this.manualInfo.iconList = allChoosedDir.direction.map(item => {
        return {
          id: item,
          color: '#454545',
          peddirection: this.getPed(allChoosedDir.peddirection)
        }
      })
      this.manualInfo.direction = allChoosedDir.direction
      this.manualInfo.peddirection = allChoosedDir.peddirection
    },
    getPed (peddirection) {
      return peddirection.map(item => {
        if (this.sidewalkPhaseData.find(ele => ele.id === item)) {
          return {
            id: item,
            name: this.sidewalkPhaseData.find(ele => ele.id === item).name
          }
        }
      })
    },
    closePhaseBack () {
      this.$emit('closeAddDrawer')
    },
    async getIntersectionInfo (agentid) {
      // 获取路口信息
      getIntersectionInfo(agentid).then(res => {
        this.phaseList = res.data.data.param.phaseList
        this.getPedPhasePos(this.phaseList)
      })
    },
    getPedPhasePos (phaseList) {
      // 行人相位信息
      this.sidewalkPhaseData = []
      phaseList.forEach((ele, i) => {
        if (ele.peddirection) {
          ele.peddirection.forEach((dir, index) => {
            // 行人相位
            if (this.PhaseDataModel.getSidePos(dir)) {
              this.sidewalkPhaseData.push({
                // key: this.CrossDiagramMgr.getUniqueKey('pedphase'),
                phaseid: ele.id, // 相位id，用于对应相位状态
                id: dir,
                name: this.PhaseDataModel.getSidePos(dir).name
              })
            }
          })
        }
      })
    },
    handleDeleteScheme () {
      this.showConfig = false
    },
    finishLoadTree () {
      this.$refs.ORGIntersectionTree.setCheckedIntersection(this.checkData)
    },
    getSerch () {
      this.$refs.ORGIntersectionTree.getDeviceRanges(this.devsfilter)
    },
    closeIcon (val) {
      this.config = !this.config
      this.agentid = val.agentid
      this.roadname = val.name
      this.getIntersectionInfo(val.agentid)
      this.manualInfo.iconList = []
      this.route.devs.forEach(item => {
        if (this.agentid === item.agentid) {
          if (!item.data) return
          this.choosedDirection = item.data.data.direction
          this.choosedPedDirection = item.data.data.peddirection
        }
      })
    },
    openIcon (val) {
      // if (val) {
      this.showCard = false
      this.showConfig = true
      this.clickChange = !this.clickChange
      // } else {
      //   this.showCard = true
      //   this.showConfig = false
      // }
    },
    deleteId (val) {
      this.checkData.map((item, index) => {
        if (item.agentid === val) {
          this.checkData.splice(index, 1)
        }
      })
      if (this.chooseId && this.chooseId !== 0) {
        this.editRoute.devs.filter(item => item.agentid !== val)
      }
      this.$refs.ORGIntersectionTree.setCheckedIntersection(this.checkData)
    },
    handleClose () {
      this.$emit('research')
    },
    reset () {
      this.activeTab = 'pattern'
    },
    checkRouteName (reqData) {
      let res = true
      let name = reqData.name
      if (!name || name.trim() === '') {
        this.$message.error(this.$t('openatc.dutyroute.emptyRouteName'))
        res = false
        return res
      }
      for (let item of reqData.devs) {
        if (name === item.name) {
          this.$message.error(this.$t('openatc.dutyroute.namerepeat'))
          res = false
          return res
        }
      }
      return res
    },
    checkRules (reqData) {
      if (!this.checkRouteName(reqData)) {
        return false
      }
      let devs = reqData.devs
      for (let inter of devs) {
        if (!inter.totaltime || inter.totaltime < 10) {
          let msg = this.$t('openatc.devicemanager.devicename') + ': ' + inter.name + ', ' + this.$t('openatc.dutyroute.lasttimeMustBeGraterThanTen')
          this.$message.error(msg)
          return false
        }
      }
      return true
    },
    onOk () {
      // check
      // let reqData = this.getReqData()
      this.route.devs.forEach(item => {
        delete item.state
        // delete item.data.data.iconList
      })
      let reqData = {
        // 'id': this.configData.id,
        'type': 2,
        'name': this.configData.name,
        'devs': this.route.devs
      }
      if (this.chooseId && this.chooseId !== 0) {
        reqData.id = this.configData.id
      }
      // if (!this.checkRules(reqData)) { // 检验方案和相位是否为空
      //   return
      // }
      UpdateViproute(reqData).then(res => {
        // let newRoute = {}
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.route = res.data.data
        // newRoute = res.data.data
        this.$message({
          message: this.$t('openatc.common.operationsuccess'),
          type: 'success',
          duration: 1500
        })
        this.reset()
        this.route.devs = this.route.devs
        this.$emit('research', this.route)
      })
    },
    getTree (data) {
      if (data.length > 0 && !this.chooseId) {
        this.showCard = true
      }
    },
    handleAdd () {
      this.showCard = true
      // this.isClose = true
      this.$refs.ORGIntersectionTree.getDeviceRanges(this.devsfilter)
    },
    cancle () {
      this.messageboxVisible = false
    },
    handleDelete () {
      this.showCard = false
    },
    onEditClick (route) {
      // this.configurationVisible = true
      this.routeData = route
    },
    setDeviceData () {
      // 获取设备表格信息
      if (this.devicesData.length === 0 && this.configData.devs && this.configData.devs.length > 0) {
        this.devicesData = [...this.configData.devs]
      } else {
        this.devicesData = []
      }
    },
    getCheck (list) {
      this.checkData = list
      let res = {
        // 'id': this.configData.id,
        'name': this.configData.name,
        'devs': []
      }
      if (this.chooseId && this.chooseId !== 0) {
        res.id = this.configData.id
      }
      let devs = []
      for (let dev of list) {
        let item = {
          'id': dev.id,
          'viprouteid': this.configData.id,
          'agentid': dev.agentid,
          'name': dev.name,
          'control': 101 // 特勤控制方式固定为101
        }
        item.data = dev.data
        let geometry = dev.geometry
        let location = dev.location
        if (geometry && geometry.coordinates && geometry.coordinates.length > 0) {
          item.geometry = geometry
        }
        if (location && location.length > 0) {
          item.location = location
        }
        devs.push(item)
      }
      res.devs = devs
      if (this.chooseId && this.chooseId !== 0) {
        let newItems = []
        list.forEach(checkDataItem => {
          const editRouteDevItem = (this.finalLists.length > 0 ? this.finalLists : this.editRoute.devs).find(editRouteDevItem => {
            return editRouteDevItem.agentid === checkDataItem.agentid
          })
          if (!editRouteDevItem) {
            newItems.push(checkDataItem)
          }
        })
        let filteredDevs = (this.finalLists.length > 0 ? this.finalLists : this.editRoute.devs).filter(editRouteDevItem => {
          return list.some(checkDataItem => {
            return editRouteDevItem.agentid === checkDataItem.agentid
          })
        })
        let order = (this.finalLists.length > 0 ? this.finalLists : this.editRoute.devs).map(item => item.agentid)
        filteredDevs.sort((a, b) => {
          return order.indexOf(a.agentid) - order.indexOf(b.agentid)
        })
        let finalList = [...filteredDevs, ...newItems]
        res.devs = finalList
        this.finalLists = []
      } else {
        // 单次点击树添加
        if (this.chooseData && this.chooseData.length > 0) {
          for (let item of this.chooseData) {
            for (let dev of res.devs) {
              if (item.agentid === dev.agentid) {
                dev.data = item.data
              }
            }
          }
          let newItems = []
          list.forEach(checkDataItem => {
            const editRouteDevItem = this.route.devs.find(editRouteDevItem => {
              return editRouteDevItem.agentid === checkDataItem.agentid
            })
            if (!editRouteDevItem) {
              newItems.push(checkDataItem)
            }
          })
          let filteredDevs = this.route.devs.filter(editRouteDevItem => {
            return list.some(checkDataItem => {
              return editRouteDevItem.agentid === checkDataItem.agentid
            })
          })
          let order = this.route.devs.map(item => item.agentid)
          filteredDevs.sort((a, b) => {
            return order.indexOf(a.agentid) - order.indexOf(b.agentid)
          })
          let finalList = [...filteredDevs, ...newItems]
          res.devs = finalList
        } else {
          if (this.route.devs) {
            if (this.route.devs.length > list.length) {
              let devs = this.route.devs.filter(item => {
                return list.some(ele => ele.agentid === item.agentid)
              })
              res.devs = devs
            }
          } else {
            res.devs = devs
          }
        }
      }
      this.route = res
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
.left-list {
  .el-card /deep/ .el-card__body {
    height: 100% !important;
    // height: 50PX;
    // line-height: 35PX;
  }
  .el-card /deep/ .vip .el-card__body {
    height: 50PX;
    background-color: #1e90c106;
    line-height: 35PX;
  }
  .control-list {
    width: 560PX;
    // height: calc(100% - 40PX);
    height: 720PX;
    position: absolute;
    left: 470PX;
    top: 20PX;
    /deep/ .el-card__body {
      // padding: 20PX 0 20PX 20PX;
      // .intersection-map .superminiCrossImg {
      //   zoom: 1.2 !important;
      //   margin-top: -144PX !important;
      // }
    }
    .roadname {
      margin-bottom:10px;
      font-size: 18PX;
      font-weight: bold;
    }
    .el-form-item {
      margin-bottom: unset;
    }
    .sure {
      position: absolute;
      right: 10PX;
      bottom: 10PX;
    }
    .schemeclose {
      position: absolute;
      font-size: 18PX;
      width: 30PX;
      height: 30PX;
      padding: unset;
      color: #909399;
      right: 5PX;
      top: 5PX;
      z-index: 999;
    }
  }
}
</style>
